package com.edu.learning.concurrent.custom.queue;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 通过Lock和 Condition实现阻塞队列
 *
 * @Author ll
 * @Date 2017/10/16 13:43
 */
public class ConditionBlockingQueue<T> implements IBlockingQueue<T> {

    private final Object[] items;
    int putStr, takeStr, count;

    public ConditionBlockingQueue() {
        this(10);
    }

    public ConditionBlockingQueue(int queueSize) {
        if (queueSize < 1) {
            throw new IllegalArgumentException("queueSize must be meaningful number");
        }
        items = new Object[queueSize];
    }

    private final Lock lock = new ReentrantLock();
    private final Condition notFull = lock.newCondition();
    private final Condition notEmpty = lock.newCondition();

    @Override
    public void put(T data) throws InterruptedException {
        lock.lock();
        try {
            while (count == items.length) {
                notFull.await();
            }
            items[putStr] = data;
            if (++putStr == items.length) {
                putStr = 0;
            }
            ++count;
            notEmpty.signal();
        } finally {
            lock.unlock();
        }
    }

    @Override
    public T take() throws InterruptedException {
        lock.lock();
        try {
            while (count == 0) {
                notEmpty.wait();
            }
            T data = (T) items[takeStr];
            if (++takeStr == items.length) {
                takeStr = 0;
            }
            --count;
            notFull.signal();
            return data;
        } finally {
            lock.unlock();
        }
    }
}
